const config = require('./config.js');
const util = require('./util.js');

function requestLogin() {
    return new Promise((resolve, reject) => {
        let code = wx.getStorageSync(config.storage.keyLoginCode);
        let systemInfo = wx.getStorageSync(config.storage.keySystemInfo);

        let reqUserObj = {
            url: config.domain.requestDomain + config.service.userLogin,
            header: {'content-type': 'application/x-www-form-urlencoded'},
            method: "POST",
            data: {
                jsCode: code,
                userSource: config.userSource,
                systemInfo: JSON.stringify(systemInfo)
            },
            success: function (res) {
                if (res.data.code == 0) {
                    // 登录成功,得到SessionId,存储sessionID
                    let sessionId = res.data.data.cSessionId;
                    wx.setStorageSync(config.storage.keySessionId, sessionId);
                    resolve(res);
                } else {
                    reject(res);
                }
            },
            fail: function (res) {
                reject(res);
            },
            complete: function (res) {

            },
        };
        wx.request(reqUserObj);
    })
}


function saveUserInfo(userInfo) {
    // return Promise.resolve();
    return new Promise((resolve, reject) => {
        let reqUserObj = {
            url: config.domain.requestDomain + config.service.saveWxUserInfo,
            header: {'content-type': 'application/x-www-form-urlencoded'},
            method: "POST",
            data: {
                ...userInfo,
                wxVersion: config.version,
                userSource: config.userSource,
                cSessionId: util.getSessionId()
            },
            complete: function () {
                resolve();
            }
        };
        wx.request(reqUserObj);
    })
}

/**
 * 联网获取用户信息。
 */
function getThirdUserInfo(userId) {
    return new Promise((resolve, reject) => {
        let reqUserObj = {
            url: config.domain.requestDomain + config.service.userInfo,
            header: {'content-type': 'application/x-www-form-urlencoded'},
            method: "POST",
            data: {
                ...userId ? {
                    userId: userId
                } : {},
                userSource: config.userSource,
                cSessionId: util.getSessionId()
            },
            success:function (res) {
                console.log("getThirdUserInfo-success", res);
                let userInfo = res.data.data;
                if(!userId){
                    wx.setStorageSync(config.storage.keyUserInfo, userInfo);
                }
                resolve(userInfo);
            }
        };
        wx.request(reqUserObj);
    });
}

module.exports = {
    requestLogin: requestLogin,
    saveUserInfo: saveUserInfo,
    getThirdUserInfo: getThirdUserInfo
};